/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.huawei.api.parser;

import com.huawei.api.bean.ClientParameter;
import com.huawei.api.exception.BaseCustomerException;

import com.beust.jcommander.JCommander;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 命令行参数解析
 *
 * @since 2023/10/28
 */
public class CommandLineParser implements Parser<String[]> {
    private static final Logger LOGGER = LoggerFactory.getLogger(CommandLineParser.class);

    private final ClientParameter clientParameter;

    public CommandLineParser() {
        this.clientParameter = new ClientParameter();
    }

    public ClientParameter getClientParameter() {
        return clientParameter;
    }

    @Override
    public void parse(String[] args) throws BaseCustomerException {
        LOGGER.info("parse input cmd line parameter");
        // 转换开始前做的操作
        if (!this.preParse()) {
            return;
        }
        // 执行转换
        this.postConvert(args);

        // 转换完之后要做的操作
        this.postParse(clientParameter);
    }

    /**
     * 转换之前
     *
     * @return true: 继续执行; false：中止执行
     */
    protected boolean preParse() {
        return true;
    }

    /**
     * 开始转换
     */
    protected void postConvert(String[] args) throws BaseCustomerException {
        try {
            JCommander commander = JCommander.newBuilder().addObject(this.clientParameter).build();
            commander.parse(args);
        } catch (Exception exception) {
            throw new BaseCustomerException("some error occur in args, please check args");
        }
    }

    /**
     * 解析完成之后的操作
     */
    protected boolean postParse(ClientParameter clientParameter) {
        // 校验参数
        return validateParameter(clientParameter);
    }

    /**
     * 校验参数
     *
     * @param clientParameter 命令行参数
     * @return 是否正确
     */
    private boolean validateParameter(ClientParameter clientParameter) {
        // 在这里校验某些参数
        return true;
    }
}
